package org.ixigua.service.wkhtmltopdf.wrapper;

import java.io.File;
import java.io.IOException;

import cn.hutool.core.lang.Assert;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.Pdf;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.WrapperConfig;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.XvfbConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * Pdf工具集成
 */
@Slf4j
public class PdfIntegration {

    private static String getWkhtmltopdfCmd(){
        return WrapperConfig.findExecutable();
    }
    public static void convertPdfFromStringTo(String content,String pdfPath) {
        //see if executable is installed
        try {
            WrapperConfig wc = new WrapperConfig(getWkhtmltopdfCmd());
            String osname = System.getProperty("os.name").toLowerCase();
            if(!osname.contains("windows")) {
                wc.setXvfbConfig(new XvfbConfig());
            }
            // GIVEN a html template containing special characters that java stores in utf-16 internally
            Pdf pdf = new Pdf(wc);
            pdf.addPageFromString(content);
            File savedPdf = pdf.saveAs(pdfPath);
            System.out.println(savedPdf.getPath());
        } catch (RuntimeException ex) {
            log.error(ex.getMessage(),ex);
        }catch (InterruptedException ex) {
            log.error(ex.getMessage(),ex);
        } catch (IOException ex) {
            log.error(ex.getMessage(),ex);
        }
    }
    public static void convertPdfFromFormUrl(String formUrl,String pdfPath){
        try{
            WrapperConfig wc = new WrapperConfig(getWkhtmltopdfCmd());
            String osname = System.getProperty("os.name").toLowerCase();
            if(!osname.contains("windows")) {
                wc.setXvfbConfig(new XvfbConfig());
            }
            // GIVEN a html template containing special characters that java stores in utf-16 internally
            Pdf pdf = new Pdf(wc);
            pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h1>Page 1</h1></html>");
            pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h1>Page 2</h1></html>");
            pdf.addPageFromUrl(formUrl);
            pdf.addPageFromString("<html><head><meta charset=\"utf-8\"></head><h1>Page 4</h1></html>");

            File savedPdf = pdf.saveAs(pdfPath);
            System.out.println(savedPdf.getPath());
        } catch (RuntimeException ex) {
            log.error(ex.getMessage(),ex);
        } catch (InterruptedException ex) {
            log.error(ex.getMessage(),ex);
        } catch (IOException ex) {
            log.error(ex.getMessage(),ex);
        }
    }

}
